function e(e) {
	return e && e.__esModule ? e : {
		default: e
	};
}
var faceconf = e(require("./face-config.js"));
var $ = getApp(), methods = require("../methods.js");
var app = $
var SocketTask = null;
var interval0;
var interval1;
var interval2;
var nowtime;
Page(Object.assign({}, methods, {
	data: {
		messageArr: [],
		msgArr: [],
		message: "",
		trimMessage: "",
		faceIconsConfig: faceconf.default,
		faceBoxShow: 0,
		scrollViewHeight: "",
		scrollTop: 1e8,
		from: "",
		page: 1,
		loading: 0,
		noMore: 0,
		show:0,
		msgtips:''
	},
	socketsend:function(senddata){
		console.log(SocketTask)
		var that = this;
		if(!SocketTask || SocketTask.readyState!=1){
			var pre_url = $.pre_url
			var wssurl = pre_url.replace('https://', "wss://") + '/wss';
			SocketTask = wx.connectSocket({url:wssurl});
			SocketTask.onOpen(function(){
				console.log('socketopen');
				SocketTask.send({data:JSON.stringify({type:'init',token:that.data.token,data:{ aid:that.data.aid,uid:that.data.uid}})})
				if(senddata){
					SocketTask.send({data:JSON.stringify(senddata)})
				}
			});
			SocketTask.onMessage(function(res){
				console.log(res)
				try{
					var data = JSON.parse(res.data);
					if(data.type == 'tokefu' || data.type == 'tokehu'){
						console.log(data.data)
						that.receiveMessage(data.data)
					}
				}catch(e){}
			})
		}else{
			if(senddata)
			SocketTask.send({data:JSON.stringify(senddata)})
		}
	},
	_onLoad: function () {
		var that = this;
		$.get($.pre_url + '/am.php?s=/kefu/message',{mid:that.options.mid},function(res){
			that.setData(res);
			that.socketsend('');
			if(res.tomember && res.tomember.nickname){
				wx.setNavigationBarTitle({
					title: res.tomember.nickname
				});
			}
			that.baseHandle();
			nowtime = res.nowtime
			interval0 = setInterval(function(){
				nowtime++;
			},1000)
			interval1 = setInterval(function(){
				that.socketsend({type:'connect',token:that.data.token});
			},25000)
		})
	},
	baseHandle: function () {
		var that = this;
		var t = 50;
		that.data.viewBarShow && (t = 94);
		this.getEleRect("container", function (e) {
			that.setData({
				scrollViewHeight: e.height - t + "px"
			});
		});
		this.getMessageList();
		interval2 = setInterval(that.updateMessageTime, 20000);
		var from = that.options.from
	},
	updateMessageTime: function(){
		var that = this;
		var messageArr = this.data.messageArr;
		messageArr.forEach(function (v, i) {
			var thistime = parseInt(v.createtime);
			var prevtime = 0;
			if(i > 0){
				prevtime = parseInt(messageArr[i-1].createtime)
			}
			if(thistime - prevtime > 600){
				v.formatTime = that.getTime(thistime, nowtime);
			}else{
				v.formatTime = '';
			}
		});
		this.setData({
			messageArr: messageArr
		});
		console.log(that.data.messageArr)
	},
	scrolltoupper: function(){
		this.getMessageList();
	},
	getMessageList: function(){
		var that = this;
		if(!that.data.loading && !that.data.noMore){
			that.setData({loading: 1});
			$.post($.pre_url + '/am.php?s=/kefu/getmessagelist',{mid:that.options.mid,pagenum:that.data.page},function(res){
				var datalist = res.data;
				if(res.status==1 && datalist.length >0) {
					that.setData({loading: 0});
					//var datalist = data.reverse();
					for(var i in datalist){
						datalist[i].content = that.transformMsgHtml(datalist[i].msgtype,datalist[i].content);
					}
					that.setData({
						messageArr: datalist.concat(that.data.messageArr)
					});
					that.updateMessageTime()
					if(that.data.page == 1){
						that.scrollToBottom()
					}else{
						//that.scrollToMiddle();
					}
					that.setData({
						page: that.data.page + 1
					});
				}
			});
		}
	},
	sendMessage: function (e){
		var that = this, message = this.data.message;
		console.log(message);
		if (message.length > 2000){
			wx.showToast({
				title: "单条消息不能超过2000字",
				icon: "none",
				duration: 1000
			});
		}else {
			if (message.replace(/^\s*|\s*$/g, "")) {
				var nowtime = Date.now();
				var msgdata = {
					aid: that.data.aid,
					mid: that.options.mid,
					uid: that.data.uid,
					msgtype: 'text',
					content:message,
					isreply:1
				}
				that.socketsend({type:'tokehu',token:that.data.token,data:msgdata});
				that.setData({
					message: "",
					trimMessage: "",
					faceBoxShow: 0
				});
			}
		}
	},
	receiveMessage: function (message) {
		var that = this;
		if(that.options.mid != message.mid){
			if(message.isreply == 0){
				var content = message.content
				if(message.msgtype=='image'){
					content ='[图片]';
				}else if(message.msgtype=='voice'){
					content ='[语音]';
				}else if(message.msgtype=='video'){
					content ='[小视频]';
				}else if(message.msgtype=='music'){
					content ='[音乐]';
				}else if(message.msgtype=='news'){
					content ='[图文]';
				}else if(message.msgtype=='link'){
					content ='[链接]';
				}else if(message.msgtype=='miniprogrampage'){
					content ='[小程序]';
				}else if(message.msgtype=='location'){
					content ='[地理位置]';
				}
				message.content = content;
				that.setData({
					show:1,
					msgtips:message
				})
				setTimeout(function () {
					that.setData({show:2})
				},10000)
			}
		}else{
			message.content = that.transformMsgHtml(message.msgtype,message.content);
			that.setData({
				messageArr: that.data.messageArr.concat([message])
			});
			setTimeout(that.updateMessageTime, 100);
			this.scrollToBottom();
			$.post($.pre_url + "/am.php?s=/kefu/isread",{mid:that.options.mid})
		}
	},
	tomessage:function(){
		var that = this;
		$.goto('message?mid=' + that.data.msgtips.mid,'redirect');
	},
	sendimg: function () {
		var that = this;
		$.chooseImage(function(data){
			for(var i = 0; i < data.length; i++){
				var message = data[i]
				var msgdata = {
					aid: that.data.aid,
					mid: that.options.mid,
					uid: that.data.uid,
					msgtype: 'image',
					content:message,
					isreply:1
				}
				that.socketsend({type:'tokehu',token:that.data.token,data:msgdata});
			}
		}, 3)
  },
	toggleFaceBox: function () {
		this.setData({
			faceBoxShow: !this.data.faceBoxShow
		});
	},
	getEleRect: function (e, a) {
		wx.createSelectorQuery().select("#" + e).boundingClientRect(function (e) {
			a && a(e);
		}).exec();
	},
	scrollToBottom: function () {
		var e = this;
		setTimeout(function () {
			e.setData({
				scrollTop: 1e10
			});
		}, 300);
	},
	scrollToMiddle: function () {
		var e = this;
		setTimeout(function () {
			e.setData({
				scrollTop: 100
			});
		}, 300);
	},
	onInputFocus: function (e) {
		this.setData({
			faceBoxShow: !1
		});
	},
	messageChange: function (e) {
		this.setData({
			message: e.detail.value,
			trimMessage: e.detail.value.trim()
		});
	},
	transformMsgHtml :function(msgtype,e) {
		if(msgtype == 'miniprogrampage'){
			var content = JSON.parse(e);
			e = '<div style="font-size:16px;font-weight:bold;height:25px;line-height:25px">'+content.Title + '</div><img src="'+content.ThumbUrl+'" width="200"/>'
		}
		if(msgtype=='image'){
			e = '<img src="'+e+'" width="200"/>'
		}
    var t = 0, n = e, o = /\[(.+?)\]/, a = o.exec(n), i = "";
    for (this.faceIds = []; null !== a; ) {
        i += n.slice(0, a.index);
        var s = faceconf.default.find(function(e) {
            return e.faceName === a[0];
        });
        i += s ? '<img width="25" height="25" src="'+ $.pre_url + '/static' + s.facePath + '" alt="" />' : a[0], 
        t = a.index + a[0].length, n = n.slice(t), a = o.exec(n);
    }
		var r = (i += n, (i = i.replace(/\n/g, "<br />")).trim());
		r = r.replace(/img\[([^\s]+?)\]/g, function(img){  //转义图片
      return '<img style="max-width:470rpx" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
    })
    return r
	},
	selectFace: function (e) {
		var a = this, t = e.target.dataset;
		this.setData({
			message: "" + a.data.message + t.faceName
		}), this.setData({
			trimMessage: a.data.message.trim()
		});
	},
	getTime:function(createtime,nowtime) {
    var t = (nowtime - createtime);
    if(t>0){
        var todaystart = new Date(this.formatTime(nowtime,"Y-m-d 00:00:00")).getTime();
				todaystart = todaystart/1000
				var lastdaystart = todaystart - 86400;
				if(t <= 180){
					return '刚刚';
				}
				if(createtime > todaystart){
					return this.formatTime(createtime, "H:i");
				}
				if(createtime > lastdaystart){
					return '昨天' + this.formatTime(createtime, "H:i");
				}
				return this.formatTime(createtime,'Y年m月d日 H:i:s');
    }
	},
	formatTime:function(time,format) {
		if(format == undefined || format == "undefined" || format == null || format == "") format = 'Y-m-d H:i:s';
		var date = new Date(time * 1000);
		var Y = date.getFullYear();
		var m = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) ;
		var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
		var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
		var i = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
		var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
		format = format.replace('Y',Y);
		format = format.replace('m',m);
		format = format.replace('d',d);
		format = format.replace('H',H);
		format = format.replace('i',i);
		format = format.replace('s',s);
		return format;
	},
	onUnload: function () {
		clearInterval(interval0);
		clearInterval(interval1);
		clearInterval(interval2);
		if(SocketTask && SocketTask.readyState==1){
			SocketTask.close();
		}
	}
}));